<?php

namespace app\api\model;


use think\Model;
use think\facade\Request;
class Auth extends  Model
{

  public function select(){
  		$level = self::where('pid',0)->all();
  	foreach ($level as $key => $value) {
  		$level[$key]['children'] = self::where('pid',$value['id'])->all()->hidden(['pid']);
  	}
  	return_json(200,'成功',$level);
  }	
  
  public function all($pagenum=1,$pagesize=1){
   $map = [];//将所有的查询条件封装到这个数组中
   //实现搜素功能
   $map =[];
   $keywords = Request::param('query');
   if(!empty($keywords)){
    //条件2
   $map[] = ['authName','like','%'.$keywords.'%'];
   }
  	$level = db('auth')->where('pid',0)->where($map)->page($pagesize,$pagenum)->select();
  	foreach ($level as $key => $value) {
  		$level[$key]['children'] = self::where('pid',$value['id'])->all()->hidden(['pid']);
  	}
  	  $count = self::where('pid',0)->count();
   
    $info = array(
      'data'=>$level,
      'total'=>$count
      );
  	return_json(200,'成功',$info);
  }

  public function del($id){

  	$res = db('auth')->field('pid')->where('id',$id)->find();
  	
  	$result=db('auth')->delete($id);
  	if($res['pid']==0){
        self::where('pid',$id)->delete();
  	}
  	if($result){
  		  return_json(200,'成功',true);
    }else{
            return_json(400,'失败',false);
    }

  }

  public function add($data){
  	 $had = self::where('authName',$data['authName'])->find();
    if($had){
        return_json(400,'失败',"该权限已存在");
    }
   
   	$res = self::save($data);
   	if($res){
   		return_json(200,'成功',true);
   	}else{
   		return_json(400,'失败',false);
   	}
  }
     public function detail($id){
        $res = db('auth')->find($id);
       if($res){
           return_json(200,'成功',$res);
       }else{
           return_json(400,'失败',false);
       }
   }

     public function edit($id,$data){
      
    
        $res = db('auth')->where('id',$id)->update($data);
       if($res){
           return_json(200,'成功',true);
       }else{
           return_json(400,'失败',false);
       }
   }

 
}
  ?>